package buildinjava.ant;

import buildinjava.Build;
import buildinjava.Project;
import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Defines a BuildInJava project.
 * 
 * @author Gili Tzabari
 */
public final class ProjectTask extends Task
{
	private final Logger log = LoggerFactory.getLogger(ProjectTask.class);
	private String name;
	private File path;
	private File buildInJavaDirectory;

	/**
	 * Sets the project name.
	 *
	 * @param name the project name
	 * @throws IllegalArgumentException if name is null
	 */
	public void setName(String name) throws IllegalArgumentException
	{
		if (name == null)
			throw new IllegalArgumentException("name may not be null");
		this.name = name;
	}

	/**
	 * Sets the project name.
	 *
	 * @param path the buildinjava directory
	 * @throws IllegalArgumentException if path is null
	 */
	public void setPath(File path) throws IllegalArgumentException
	{
		if (path == null)
			throw new IllegalArgumentException("path may not be null");
		this.path = path;
	}

	/**
	 * Sets the buildinjava installation directory.
	 *
	 * @param buildInJava the buildinjava installation directory
	 * @throws IllegalArgumentException if buildinjava is null
	 */
	public void setBuildInJava(File buildInJava) throws IllegalArgumentException
	{
		if (buildInJava == null)
			throw new IllegalArgumentException("buildinjava may not be null");
		this.buildInJavaDirectory = buildInJava;
	}

	@Override
	public void execute() throws BuildException
	{
		if (name == null)
			throw new BuildException("name must be specified");
		if (path == null)
			throw new BuildException("path must be specified");
		if (log.isTraceEnabled())
			log.trace("{}", this);
		Build build = new Build(buildInJavaDirectory, path);
		Project projectInstance = build.buildProject();
		if (projectInstance == null)
		{
			throw new BuildException("buildinjava.Project.Builder not found at " + build.getBuildDirectory().
				getAbsolutePath());
		}
		InjectorProvider.getInjector().getInstance(ProjectProvider.class).putProject(name,
			projectInstance);
		super.execute();
	}

	@Override
	public String toString()
	{
		return getClass().getName() + "[name=" + name + ", path=" + path + "]";
	}
}
